package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RemoveItemFromCartServlet", value = "/RemoveItemFromCartServlet")
public class RemoveItemFromCartServlet extends HttpServlet {

    private String workingItemId;
    private Cart cart;
    private LogService logService = new LogService();
    private CartService cartService = new CartService();

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        workingItemId = request.getParameter("workingItemId");
        HttpSession session = request.getSession();
        cart = (Cart)session.getAttribute("cart");
        Item item = cart.removeItemById(workingItemId);
        Account account = (Account)session.getAttribute("account");
        cartService.removeItemById(account.getUsername(),workingItemId);



        if(account != null){
            String logInfo = logService.logInfo(" ") + " " + item + " 已从购物车中移除";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        request.getRequestDispatcher(VIEW_CART).forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
